package cn.zz.veggie.model.query;

import java.util.Collection;
import java.util.Objects;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;

import cn.zz.comm.core.types.query.PageQuery;
import cn.zz.comm.util.StrUtil;
import cn.zz.veggie.model.domain.DelMan;

/**
 * @author zhongq
 * @since 2024/7/14
 */
public class DelManQuery {
	public static final int DB_PATTERN_ID = -1;
	public static final int DB_PATTERN_BRIEF_FILED = -2;

	public Integer id;
	public Collection<Integer> ids;
	public String username;
	public String likeMobile;
	public String mobile;
	public String likeUsername;
	public int columnPattern;

	public static DelManQuery ofKeyword(String keyword) {
		final DelManQuery query = new DelManQuery();
		query.likeUsername = StrUtil.blankToNull(keyword);
		return query;
	}

	public LambdaQueryWrapper<DelMan> toQueryWrapper() {
		final LambdaQueryWrapper<DelMan> queryWrapper = Wrappers.lambdaQuery();

		injectColumn(queryWrapper);

		queryWrapper.eq(Objects.nonNull(id), DelMan::getId, id);
		queryWrapper.in(Objects.nonNull(ids), DelMan::getId, ids);
		queryWrapper.eq(Objects.nonNull(mobile), DelMan::getMobile, mobile);
		queryWrapper.like(Objects.nonNull(likeMobile), DelMan::getMobile, likeMobile);
		queryWrapper.like(Objects.nonNull(likeUsername), DelMan::getUsername, likeUsername);
		return queryWrapper;
	}

	private void injectColumn(LambdaQueryWrapper<DelMan> queryWrapper) {
		switch (columnPattern) {
		case DB_PATTERN_ID -> queryWrapper.select(DelMan::getId);
		case DB_PATTERN_BRIEF_FILED -> queryWrapper.select(DelMan::getId, DelMan::getUsername);
		}
	}

	public Page<DelMan> toPage(PageQuery p) {
		Page<DelMan> page = Page.of(p.getCurrent(), p.getSize());
		// TODO 2024/7/13 10:12 DeliveryMan by
		page.setOptimizeCountSql(p.isOptimizeCountSql());
		page.setSearchCount(p.isSearchCount());
		page.setOptimizeJoinOfCountSql(p.isOptimizeJoinOfCountSql());
		page.setCountId(p.getCountId());
		return page;
	}
}